//
//  Status.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/18.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit
import SDWebImage

class Status: NSObject {

    // 获取当前登录用户及其所关注用户的最新微博
    let WB_Home_Timeline_URL = "https://api.weibo.com/2/statuses/home_timeline.json"
    
    // 微博创建时间
    var created_at : String?
    
    // 微博ID
    var id : Int = 0
    
    // 微博的征文
    var text : String?
    
    // 微博来源
    var source : String?
    
    // 微博作者的用户信息
    var user : User?
    // 转发微博记录
    var retweeted_status : Status?
    
    // 配图的数组
    var pic_urls : [[String:String]]? {
        didSet {
            // 实例化数组
            imgUrls = [NSURL]()
            largeUrls = [NSURL]()
            // 遍历数组 
            for dict in pic_urls!{
                if let urlString = dict["thumbnail_pic"]{
                    let largeUrl = (urlString as NSString).stringByReplacingOccurrencesOfString("thumbnail", withString: "large")
                    
                    // 拼接缩略图和大图的url
                    imgUrls?.append(NSURL(string: urlString)!)
                    largeUrls?.append(NSURL(string: largeUrl)!)
                }
            }
        }
    }
    
    // 配图的url数组
    var imgUrls : [NSURL]?
    // 大图的url数组
    var largeUrls : [NSURL]?
    
    // 如果是转发的微博  转发人是没有图片的
    // 是转发微博  就返回转发微博的图片
    // 如果不是  返回微博图片
    var pictureUrls: [NSURL]?{
        return retweeted_status == nil ? imgUrls : retweeted_status?.imgUrls
    }
    
    var largePicUrls : [NSURL]?{
        return retweeted_status == nil ? largeUrls : retweeted_status?.largeUrls
    }
    
    // 转发数
    var reposts_count : Int = 0
    // 评论数
    var comments_count : Int = 0
    // 表态数
    var attitudes_count : Int = 0
    // 属性数组
    static let properties = ["created_at", "id", "text", "source", "reposts_count", "comments_count", "attitudes_count", "pic_urls"]
    
    init(dict: [String : AnyObject]){
        super.init()
        
        for key in Status.properties {
            if dict[key] == nil {
                continue
            }
            self.setValue(dict[key], forKey: key)
        }
        // 单独处理user
        if let userDict = dict["user"] as? [String : AnyObject] {
            user = User(dict: userDict)
        }
        // 单独处理转发微博
        if dict["retweeted_status"] != nil {
            retweeted_status = Status(dict: dict["retweeted_status"] as! [String : AnyObject])
        }
    }
    
    /// 加载微博数据
    class func loadStatuses (since_id : Int,max_id : Int ,completion:(statuses: [Status]?) -> ()){
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        assert(sharedUserAccount?.access_token != nil, "用户数据加载错误")
        
        var params = ["access_token" : sharedUserAccount!.access_token]
        // 如果不存在since_id  默认为0
        if since_id > 0 {
            params["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            params["max_id"] = "\(max_id - 1)"
        }
        
        NetWorkTools.requestJSON(.GET, URLString: urlString, parameters: params) { (json) -> () in
            if let array = (json as! NSDictionary)["statuses"] as? [[String: AnyObject]] {
                
                let result = self.statuses(array)
                self.cacheStatusImage(result, completion: completion)
                return
            }
            completion(statuses: nil)
        }
    }
    
    /// 缓存微博数据中得图像
    private class func cacheStatusImage(statuses : [Status]?, completion: (statuses : [Status]?) -> ()){
        
        if statuses == nil {
            completion(statuses: nil)
            return
        }
        
        var group = dispatch_group_create()
        
        for status in statuses as [Status]! {
            if status.pictureUrls == nil {
                continue
            }
            
            for url in status.pictureUrls! {
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: nil, progress: nil, completed: { (_, _, _, _, _) -> Void in
                    dispatch_group_leave(group)
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            completion(statuses: statuses)
        }
        
    }
    
    private class func statuses (array : [[String : AnyObject]]) -> [Status]?{
        if array.count == 0 {
            return nil
        }
        
        var arrayM = [Status]()
        for dict in array {
            arrayM.append(Status(dict: dict))
        }
        return arrayM
        
    }
    
}
